//
//  HTFrameSysUtils.m
//  HTERPManApp
//
//  Created by standychen on 14-11-11.
//  Copyright (c) 2014年 HT. All rights reserved.
//
// SQLite访问——frmdb开源框架

#import "HTFrameSysUtils.h"
#import "FMDB.h"


static NSString *_connectionStr=@"";//连接串
static NSString *_dbName=@"";//数据库名


@implementation HTFrameSysUtils

//设置数据库连接串
+(void)dbNameSet:(NSString *)str
{
    _dbName=str;
    //获得沙盒路径Documents文件夹
    NSString *homePath = NSHomeDirectory();
    _connectionStr = [NSString stringWithFormat:@"%@/Documents/%@.sqlite",homePath,_dbName];//
    
    
    [self checkSqliteDBVersion];
}


//检查数据库版本
+(void)checkSqliteDBVersion
{
    //获得沙盒路径Documents文件夹
    NSString *homePath = NSHomeDirectory();
    NSString *path = [NSString stringWithFormat:@"%@/Documents/%@.sqlite",homePath,_dbName];//todolist.plist
    
    NSFileManager *filem=[NSFileManager defaultManager];
    if (![filem fileExistsAtPath:path]) {//如果不存在拷贝
        
        NSString *sourcePath=[[NSBundle mainBundle] pathForResource:_dbName ofType:@"sqlite"];
        [filem copyItemAtPath:sourcePath toPath:path error:nil];
    }
    else//如果存在则检查数据库版本是否最新
    {
        
    }
    
    NSLog(@"path = %@",path);
    
}

//获得执行数据库操作对象;待改进为直接操作，目前先这样，不用每个地方都控制访问数据库
//complete:(void(^)(NSString *backstr))block
+(void)getFMDataBase:(void(^)(FMDatabase *dbobj))block
{
    FMDatabase *db = [FMDatabase databaseWithPath:_connectionStr];
    
    if ([db open]) {
       
        block(db);
        
        [db close];
    }
}

//执行查询
+(void)Fill:(NSString *)sql
{
    FMDatabase *db = [FMDatabase databaseWithPath:_connectionStr];
    
    if (db.open) {
        
        //返回的是一个结果集
        //FMResultSet *set = [db executeQuery:sql];
        
//        NSDictionary *dict=[[NSDictionary alloc] init];
//        while ([set next]) {
//            NSString *colname=[set]
//        }
//        todolist=[[NSMutableArray alloc]init];
//        [todolist removeAllObjects];
//        
//        while ([set next]) {
//            
//            //int jobid = [set intForColumnIndex:0];
//            
//            NSString *title = [set stringForColumnIndex:0];
//            
//            //int jobmoney = [set intForColumnIndex:2];
//            
//            //int jobmoney = [set intForColumn:@"jobmoney"];
//            
//            NSDate *createtime = [set dateForColumnIndex:1];
//            
//            //创建对象
//            Task *task = [[Task alloc]initWithTitle:title andTime:createtime];
//            [todolist addObject:task];
//        }
        [db close];
    }

}

//执行增删改语句
+(void)ExcuteNonQuery:(NSString *)sql
{
//    FMDatabase *db = [FMDatabase databaseWithPath:_connectionStr];
//    
//    if ([db open]) {
//        
//        //sql语句后跟参数，参数必须是对象
//        BOOL res = [db executeUpdate:sql];
//        
//        if (res) {
//            NSLog(@"SUCCESS!");
//        }
//        [db close];
//    }
}

@end
